<?php

namespace App\Http\Controllers\Personal;
use App\Models\Common\CollOption;
use App\Models\Personal\ResumeEducationExp;
use App\Models\Personal\ResumeWorkExp;
use App\Models\Personal\ResumeProjectExp;
use App\Models\Personal\ResumeLanguageSkill;
use App\Models\Personal\ResumeSkill;
use App\Models\Personal\ResumeCertificate;
use App\Models\Personal\ResumeOther;
use App\Models\Personal\ResumeWorks;
use Illuminate\Http\Request;
use App\Http\Requests\Personal\resumeRefresh\resumeRefreshRequest;
use App\Models\Personal\Resume;
use Illuminate\Support\Facades\DB;
use Style;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use App\Models\XS\JobXS;

class WelcomeController extends CommonController{
    /**
     * 个人账户中心
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request ){
        $user = auth()->guard('personal')->user();
        //显示默认简历
        $resumeInfo = Resume::where('uid',$user->uid)->where('default','1')->first();
        //completion 数组中的 1 代表已经完成 0代表未完成
        $percentage = 0;
        $completionArr = [1,0,0,0,0,0,0,0,0,0,0,0,0];
        $similarJobs = [];
        if($resumeInfo){
            //最近工作经历
            $work = ResumeWorkExp::where('uid',$user->uid)->where('resume_id',$resumeInfo->id)
                ->select('post','company')->orderBy('starttime','desc')->first();
            //最高学历
            $edu = ResumeEducationExp::where('uid',$user->uid)->where('resume_id',$resumeInfo->id)
                ->select('school','speciality','education')->orderBy('starttime','desc')->first();
            //获取百分比
            if(!empty($resumeInfo->intentionjobs)) $completionArr[1] = 1;
            if(!empty($resumeInfo->introduction)) $completionArr[2] = 1;
            if($work) $completionArr[3] = 1;
            if($edu) $completionArr[4] = 1;
            if(ResumeProjectExp::where('uid',$user->uid)->where('resume_id',$resumeInfo->id)->count() > 0) $completionArr[5] = 1;
            if(ResumeLanguageSkill::where('uid',$user->uid)->where('resume_id',$resumeInfo->id)->count() > 0) $completionArr[6] = 1;
            if(ResumeSkill::where('uid',$user->uid)->where('resume_id',$resumeInfo->id)->count() > 0) $completionArr[7] = 1;
            if(ResumeCertificate::where('uid',$user->uid)->where('resume_id',$resumeInfo->id)->count() > 0) $completionArr[8] = 1;
            if(ResumeOther::where('uid',$user->uid)->where('resume_id',$resumeInfo->id)->count() > 0) $completionArr[9] = 1;
            if(ResumeWorks::where('uid',$user->uid)->where('resume_id',$resumeInfo->id)->count() > 0) $completionArr[10] = 1;

            //适合您的岗位
            if (\Site::get('xsOpen')) {
                $similarJobs = $this->xunCommend($resumeInfo,$request);
                if ($similarJobs->total() < 1); $similarJobs = $this->sqlCommend($resumeInfo,$request);
            }
            else {
                $similarJobs = $this->sqlCommend($resumeInfo,$request);
            }
        }else{
            $resumeInfo = $user;
        }
        $user->mobile = !empty($user->mobile) ? str_limit($user->mobile ,12) : '未绑定手机';
        $user->email = !empty($user->email) ? str_limit($user->email ,24) : '未绑定邮箱';
        $resumeInfo->name = !empty($resumeInfo->name) ? $resumeInfo->name : '未填写名字';
        $resumeInfo->mobile = !empty($resumeInfo->mobile) ? str_limit($resumeInfo->mobile ,12) : '';
        $resumeInfo->email = !empty($resumeInfo->email) ? str_limit($resumeInfo->email ,24) : '';
        $resumeInfo->job_status_val = !empty($resumeInfo->job_status) ? CollOption::getOptionName($resumeInfo->job_status,'job_status') : '未填写';
        $resumeInfo->intentionjobs = !empty($resumeInfo->intentionjobs) ? $resumeInfo->intentionjobs : '未填写';
        $resumeInfo->expectedsalary = !empty($resumeInfo->expectedsalary) ? $resumeInfo->expectedsalary.'元/月' : '未填写';
        $resumeInfo->isexpectedsalary = !empty($resumeInfo->isexpectedsalary) ? $resumeInfo->isexpectedsalary : '';
        $resumeInfo->refreshtime = !empty($resumeInfo->updatetime) ? $resumeInfo->updatetime : '';
        $resumeInfo->updatetime = !empty($resumeInfo->updatetime) ? substr($resumeInfo->updatetime,0,10) : '未填写简历';
        $resumeInfo->avatar = !empty($resumeInfo->avatar) ? asset('upload/personalavatar/'.$resumeInfo->avatar) : asset('default/images/personal/headPortrait.jpg');

        $resumeInfo->post = !empty($work->post) ? $work->post : '';
        $resumeInfo->company = !empty($work->company) ? $work->company : '';
        $resumeInfo->education = !empty($edu->education) ? CollOption::getOptionName($edu->education,'education') : '';
        $resumeInfo->school = !empty($edu->school) ? $edu->school : '';
        $resumeInfo->speciality = !empty($edu->speciality) ? $edu->speciality : '';
        //审核状态
        switch($resumeInfo->resume_status){
            case 0:$resumeInfo->status = '审核中..';break;
            case 1:$resumeInfo->status = '完全公开';break;
            case 2:$resumeInfo->status = '不公开简历';break;
            case 3:$resumeInfo->status = '完全保密简历';break;
            case 4:$resumeInfo->status = '审核不通过';break;
            case 5:$resumeInfo->status = '审核不通过';break;
        }
        //百分比
        for($i=0;$i<11;$i++){
            if($i == 8 || $i == 9){
                if($completionArr[$i] == 1){
                    $percentage += 5;
                }
            }else{
                if($completionArr[$i] == 1){
                    $percentage += 10;
                }
            }
        }
        $resumeInfo->percentage = $percentage;
        //隐私
        $resumeInfo->resume_status = ($resumeInfo->resume_status !=0 and $resumeInfo->resume_status !=4 ) ? $resumeInfo->resume_status : $resumeInfo->bkresume_status;
        //面试通知记录条数
        $interviewCount = DB::table('interview as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            ->join('company_job as t3', 't1.job_id', '=', 't3.id')
            ->select('t1.id')
            ->where('t1.personal_uid',$user->uid)
            ->where('t1.status','!=',4)
            ->count();
        $resumeInfo->interviewCount = ($interviewCount > 0 ) ? $interviewCount : 0 ;
        //简历投递记录条数
        $resumeSendCount = DB::table('resume_send as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            ->join('company_job as t3', 't1.job_id', '=', 't3.id')
            ->select('t1.id')
            ->where('t1.personal_uid',$user->uid)
            ->where('t1.resume_id', $resumeInfo->id)
            ->where('t1.status','!=',4)
            ->count();
        $resumeInfo->resumeSendCount = ($resumeSendCount > 0 ) ? $resumeSendCount : 0 ;
        //谁浏览了我记录条数
        $browseResumeCount = DB::table('browse_resume as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            ->join('company_users as t3', 't1.company_uid', '=', 't3.uid')
            ->select('t1.id')
            ->where('t1.personal_uid',$user->uid)
            ->count();
        $resumeInfo->browseResumeCount = ($browseResumeCount > 0 ) ? $browseResumeCount : 0 ;
        //简历下载记录条数
        $buyResumeCount = DB::table('buy_resume as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            ->join('company_users as t3', 't1.company_uid', '=', 't3.uid')
            ->select('t1.id')
            ->where('t1.personal_uid',$user->uid)
            ->where('t1.resume_id',$resumeInfo->id)
            ->count();
        $resumeInfo->buyResumeCount = ($buyResumeCount > 0 ) ? $buyResumeCount : 0 ;
        return Style::view('personal.welcome',compact('user','resumeInfo','similarJobs'));
    }

    /**
     * ajax刷新简历提交
     * @param resumeRefreshRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function ajaxRefresh(resumeRefreshRequest $request){
        $user = auth()->guard('personal')->user();
        $input = $request->only(['id','work_year','mobile','email','qq','address']);
        if($request -> uptype == 1){
            $input['updatetime'] = date('Y-m-d H:i:s',time());
        }
        $result = Resume::where('id',$request->id)->where('uid',$user->uid)->update($input);
        if($result){
            return response()->json(['status' => 0,'msg' => '更新简历成功！']);
        }else{
            return response()->json(['status' => 1,'msg' => '更新简历数据和原数据相同！']);
        }
    }

    protected function xunCommend($resumeInfo, $request) {
        //从xunsearch讯搜中找出推荐职位
        $q=[];

        $jobsort=[];//所属岗位
        for ($i=1;$i<=5;$i++) {
            $sort=$resumeInfo->{'jobsort' . $i};
            if (!empty($sort)) {
                $jobsort[]=$sort;
            }
        }
        $q['jobsort']=$jobsort;

        $keyword = [];
        $keyword[] = $resumeInfo->intentionjobs;//意向岗位
        $q['keyword'] = $keyword;
        $q['by_day'] = true;

        $jobxs = new JobXS();
        $page = $request->input('page', 1);
        //搜索(参数:搜索条件,第几页,一页个数,获取总数,是否按照时间排序)
        $arr = $jobxs->searchJob($q, $page,18,true,true);
        return $this->pageInfo($arr['data'],$arr['total'],$request);
    }

    protected function sqlCommend($resumeInfo, $request) {
        $job = DB::table('company_job as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            ->select(
                't1.job_title','t1.id','t1.com_id','t1.salary_above','t1.salary_below','t1.updatetime',
                't2.company_name'
            )
            ->where('job_status', 1)//审核通过的职位
            ->where(function ($query) use($resumeInfo) {
                for($i=1;$i<=5;$i++) {
                    $value = $resumeInfo->{'jobsort' . $i};
                    if (!empty($value)) {
                        $query->orWhere('t1.job_category1', '=',$value)
                            ->orWhere('t1.job_category2', '=', $value)
                            ->orWhere('t1.job_category3', '=', $value)
                            ->orWhere('t1.job_category4', '=', $value)
                            ->orWhere('t1.job_category5', '=', $value);
                    }
                }
            });
        $count = $job->count();
        $jobs = $job->orderBy('t1.updatetime', 'desc')->orderBy('t1.id','desc')
            ->skip($this->getSkip($request->page))->take(18)->get();
        return $this->pageInfo($jobs,$count,$request);
    }

    /**
     * 分页信息
     */
    protected function pageInfo($data,$total,$request){
        $perPage = 18;//每页显示18条
        $current_page = $request->input('page',1);
        $total=$total>(18*200)?(18*200):$total;
        $company_job = new LengthAwarePaginator($data, $total, $perPage, $current_page,[
            'path' => Paginator::resolveCurrentPath(), //注释2
            'pageName' => 'page',
        ]);
        return $company_job;
    }

    /**
     * 取得分页启始数
     */
    protected function getSkip($page){
        if(empty($page)) $page=1;
        if($page>200) $page=200;
        return ($page-1)*18;
    }
}